Page({
  data: {
    name: '',
    sex: 0,
    phone: '',
    address: '',
    doorNo: '',
    tag: '公司',
    idx: null,
    isEdit: false
  },
  onLoad(options) {
    if (options && options.idx !== undefined) {
      const idx = Number(options.idx);
      const list = wx.getStorageSync('addressList') || [];
      const item = list[idx];
      if (item) {
        this.setData({
          name: item.name,
          sex: item.sex,
          phone: item.phone,
          address: item.address,
          doorNo: item.doorNo,
          tag: item.tag,
          idx,
          isEdit: true
        });
      }
    }
  },
  onInputName(e) {
    this.setData({ name: e.detail.value });
  },
  onSelectSex(e) {
    this.setData({ sex: Number(e.currentTarget.dataset.sex) });
  },
  onInputPhone(e) {
    this.setData({ phone: e.detail.value });
  },
  onInputAddress(e) {
    this.setData({ address: e.detail.value });
  },
  onAutoFillPhone() {
    // 可用 wx.getUserProfile 或 wx.getPhoneNumber 获取手机号
    wx.showToast({ title: '自动填充', icon: 'none' });
  },
  onChooseAddress() {
    wx.showToast({ title: '选择地址', icon: 'none' });
  },
  onInputDoorNo(e) {
    this.setData({ doorNo: e.detail.value });
  },
  onSelectTag(e) {
    this.setData({ tag: e.currentTarget.dataset.tag });
  },
  onSave() {
    const { name, sex, phone, address, doorNo, tag, idx, isEdit } = this.data;
    if (!name || !phone || !address) {
      wx.showToast({ title: '请填写完整', icon: 'none' });
      return;
    }
    let list = wx.getStorageSync('addressList') || [];
    const newItem = { name, sex, phone, address, doorNo, tag };
    if (isEdit && idx !== null && list[idx]) {
      list[idx] = newItem;
    } else {
      list.unshift(newItem);
    }
    wx.setStorageSync('addressList', list);
    wx.showToast({ title: '保存成功', icon: 'success' });
    setTimeout(() => {
      wx.navigateBack();
    }, 500);
  },
  onDelete() {
    const { idx } = this.data;
    let list = wx.getStorageSync('addressList') || [];
    if (idx !== null && list[idx]) {
      list.splice(idx, 1);
      wx.setStorageSync('addressList', list);
      wx.showToast({ title: '已删除', icon: 'success' });
      setTimeout(() => {
        wx.navigateBack();
      }, 500);
    }
  }
}); 